﻿using ACServerSelfHost.Properties;
using Microsoft.Owin.Hosting;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace ACServerSelfHost
{
    class Program
    {
        // args is not needed
        // static void Main(string[] args)
        static void Main()
        {
            Uri baseAddress = new UriBuilder(scheme: "http", host: Settings.Default.HostAddress, portNumber: Settings.Default.HostPort).Uri;

            WebAppHost appHost = new WebAppHost(baseAddress);

            // Set title for the window
            Console.Title = string.Format(CultureInfo.CurrentCulture, Resources.ConsoleTitle, appHost.BaseAddress.AbsoluteUri);

            Log.Write(string.Format(CultureInfo.CurrentCulture, Resources.LogStartingHost, appHost.BaseAddress.AbsoluteUri), Log.Target.Info);

            // Start OWIN host 
            try
            {
                appHost.State = HostStates.Run;

                appHost.HostStatusChanged += (sender, e) =>
                    {
                        switch (e.CurrentStatus)
                        {
                            case HostStates.Stop:
                                {
                                    Log.Write(Resources.LogHostStopRequest, Log.Target.Info);
                                    break;
                                }
                            case HostStates.Restart:
                                {
                                    Log.Write(Resources.LogHostRestartRequest, Log.Target.Info);
                                    break;
                                }
                            default:
                                break;
                        }
                    };

                appHost.LogNotification += (sender, e) =>
                    {
                        Log.Write(e.Message, e.LogTarget);
                    };

                // TestOutputTimer();

                while (appHost.State != HostStates.Stop)
                {
                    using (WebApp.Start<ACServerApi.Startup>(url: baseAddress.AbsoluteUri))
                    {
                        if (appHost.State == HostStates.Restart)
                        {
                            appHost.State = HostStates.Run;
                        }

                        Log.Write(Resources.LogHostStarted, Log.Target.Info);

                        while (appHost.State == HostStates.Run )
                        {
                            Console.Write(Resources.ConsolePrompt, appHost.Name);
                            ConsoleColor originalColor = Console.ForegroundColor;
                            Console.ForegroundColor = ConsoleColor.White;

                            //ConsoleKeyInfo cki;
                            //bool done = false;
                            //string inputText = "";
                            //while (!done)
                            //{
                            //    cki = Console.ReadKey(true);
                            //    if (cki.Key == ConsoleKey.Escape)
                            //    {
                            //        break;
                            //    }
                            //    //var prefix = appHost.CommandList.Where(c => c.Prefixes.Any(p => p.StartsWith(cki.KeyChar.ToString()))).Select(p=>p.Prefixes.First());

                            //    var prefixes = from c in appHost.CommandList
                            //               from p in c.Prefixes
                            //               where p.StartsWith(cki.KeyChar.ToString())
                            //               select p;
                            //    var prefixesList = prefixes.ToList();
                            //    if (prefixesList.Count > 0)
                            //    {
                            //        Console.Write(prefixes.ToList()[0]);
                                    
                            //    }
                            //}

                            string commandInput = Console.ReadLine();

                            if (string.IsNullOrWhiteSpace(commandInput))
                            {
                                continue;
                            }

                            try
                            {
                                appHost.ExecuteCommand(commandInput);
                            }
                            catch (Exception ex)
                            {
                                Log.Write(ex.Message, Log.Target.Error);
                            }
                            Console.ForegroundColor = originalColor;
                        }

                    }
                    Log.Write(Resources.LogHostStopped, Log.Target.Info);
                }
            }
            catch (Exception ex)
            {
                appHost.State = HostStates.Stop;
                Log.Write(string.Format(CultureInfo.CurrentCulture, Properties.Resources.UnhandledExceptionPressKey, ex.Message), Log.Target.Error);
                Console.ReadLine();
            }
            finally
            {

            }
        }

        //private static void TestOutputTimer()
        //{
        //    using (System.Timers.Timer t = new System.Timers.Timer())
        //    {
        //        t.Elapsed += (sender, e) => { Log.Write("Ping!"); };
        //        t.Interval = 5000;
        //        t.Enabled = true;
        //    }
        //}
    }
}
